<?php
##############################################
#
#   菜单配置
# @ Time：2016-12-9 - 上午12:00:09
# @ Author ：JiangYongWei <1085562810@qq.com>
# @ Encoding ：UTF-8 language ：PHP
#
##############################################

namespace Admin\Model;
use Admin\Model\Data;

class RuleModel extends AdminBaseModel{
	/* 用户组表  */
	protected $tableName = 'auth_rule';	
	
	protected $_db;
	
	public function __construct($tableName=''){
		//初始化数据库对象
		$this -> _db = M();
		if(!empty($tableName)){
			$this -> tableName = $tableName;
		}	
		parent::__construct($this -> tableName);
	}
	
	/**
	 * 获取权限管理
	 * @param string $type
	 * @param string $order
	 * @param string $name
	 * @param string $child
	 * @param string $parent
	 * @return Ambigous <multitype:, multitype:unknown , unknown>
	 */
	public function getTreeData($type='tree', $order='', $name='name', $child='id', $parent='p_id'){
		// 判断是否需要排序
		if(empty($order)){
			$data = $this -> select();
		}else{
			$data = $this -> order($order.' is null,'.$order) -> select();
		}
		// 获取树形或者结构数据
		if($type == 'tree'){
			$data = \Org\Nx\Data::tree($data, $name, $child, $parent);
		}elseif($type = "level"){
			$data = \Org\Nx\Data::channelLevel($data, 0, '&nbsp;' ,$child);
		}
		return $data;
	}
	
	/**
	 * 添加权限
	 * @param array $data
	 */
	public function addRule($data){
		$sql = "insert into mt_auth_rule values(default, {$data['pid']}, '{$data['name']}',
												'{$data['title']}', default, default, default)";
		return $this -> _db -> execute($sql);
	}
	
	/**
	 * 删除菜单
	 * @param int $id
	 */
	public function deleteRule($id){
		//判断是否有父级菜单存在
		$data = $this -> _db -> query("select id from mt_auth_rule where p_id = $id");
	
		if(count($data) > 0){
			return 1;
		}else{
			$result = $this -> _db -> execute("delete from mt_auth_rule where id = $id");
			if($result)
				return 2;
			else
				return 3;
		}
	}
	
	/**
	 * 修改权限
	 * @param array $data
	 */
	public function editRule($data){
		$sql = "update mt_auth_rule set name = '{$data['name']}', title = '{$data['title']}'
		where id = {$data['id']}";
		return $this -> _db -> execute($sql);
	}
}